package com.icity.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.icity.common.Result;
import com.icity.entity.Menu;
import com.icity.entity.Role;
import com.icity.entity.RoleMenu;
import com.icity.entity.treemenu;
import com.icity.entity.twotreemenu;
import com.icity.entity.system.TableSupport;
import com.icity.service.SystemRoleService;
import com.icity.util.IdUtils;

@RestController
@RequestMapping(value = "/admin/system")
public class SystemRoleController {

	@Autowired
	private SystemRoleService systemRoleService;

	
	@RequestMapping(value = "/Roletable")
	@ResponseBody
	public Result getMenuList(HttpServletRequest request) {
		int page = Integer.parseInt(request.getParameter("page"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		String name = request.getParameter("name");
	
		Map<Object,Object> map = new HashMap<Object,Object>();

		if (!name.equals("undefined")) {
			map.put("name", name);
		}
		
		Result result = new Result();
		try {
		
			map.put("page", (page-1)*limit);
			map.put("limit", limit);
			TableSupport<Role> list = (TableSupport<Role>) systemRoleService.getRoleLsit(map);
			result.setCode("1");
			result.setMessage("获取成功");
			result.setData(list);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
	}
	
	
	
	
	
	
	
	@PostMapping(value = "/roleSaves")
	@ResponseBody
	public Result roleSaves(HttpServletRequest request,Role role){
		Result result = new Result();
		role.setUnique_code(IdUtils.uuid());
		role.setCreate_time(new Date());
		role.setUpdate_time(new Date());
		
		try {
			
			boolean flag = systemRoleService.isExitroleByName(role.getId());
			System.out.println("flag:"+flag);
			int datas = 0;
			if(flag==true){
				datas = systemRoleService.updateRole(role);
			}else{
				datas = systemRoleService.saveRole(role);
				
			}
			result.setCode("1");
			result.setMessage("获取成功");
			result.setData(datas);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
	}

   
   /**
     * 删除
    */
	@RequestMapping(value = "/role/delete")
	@ResponseBody
	public Result deleteRole(HttpServletRequest request) {
		int id = Integer.parseInt(request.getParameter("ids"));
		Result result = new Result();
		try {
			int data = systemRoleService.deleteRoleById(id);
			result.setCode("1");
			result.setMessage("获取成功");
			result.setData(data);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
	}
	
	/*@RequestMapping(value = "/selectmenus")
	@ResponseBody
	public Result selectmenu(HttpServletRequest request) {
		Result result = new Result();
		try {
			
			 //原始的数据
			List<Menu> rootCate = systemRoleService.onemen();//一级分类
		   
		    // 最后的结果
		    List<Menu> cateFinalList = new ArrayList<Menu>();
		    // 先找到所有的一级菜单
		    for (int i = 0; i < rootCate.size(); i++) {
		        //一级菜单没有pid
		        if ("0".equals(rootCate.get(i).getParent_code())) {
		        	cateFinalList.add(rootCate.get(i));
		        }
		    }
		    // 为一级菜单设置子菜单，getChild是递归调用的
		    for (Menu menu : cateFinalList){
		    	menu.setChildCates(getChild(menu.getUnique_code(), rootCate));
		    }
		 
			result.setCode("1");
			result.setMessage("获取成功");
			result.setData(cateFinalList);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
		
		
		
	}*/
	
	
	/*private List<Menu> getChild(String id, List<Menu> rootCate) {
	    // 子菜单
	    List<Menu> childList = new ArrayList<>();
	    for (Menu cate : rootCate) {
	        // 遍历所有节点，将父菜单id与传过来的id比较
	        if (StringUtils.isNotBlank(cate.getParent_code())) {
	            if (cate.getParent_code().equals(id)) {
	                childList.add(cate);
	                cate.setChildCates(getChild(cate.getUnique_code(), rootCate));
	            }
	        }
	    }
	    //递归退出条件
	    if (childList.size() == 0) {
	        return null;
	    }
	    return childList;
	}*/
	/**
	 * 添加角色菜单
	 * @param request
	 * @return
	 */
	@PostMapping(value = "insertrolemenu")
	@ResponseBody
	public Result insertrolemenu(HttpServletRequest request) {
	   
		Result result = new Result();				
		try {						
			String roleId=request.getParameter("roleId");
			//获取所有菜单id
			String moduleIds = request.getParameter("moduleIds");
		   String ids=	moduleIds.replace("\"", "").replace("[", "").replace("]", "");
		//	String[]  moduleId = moduleIds.split("\"");
		   String[]  moduleId = ids.split(",");
			for (String string : moduleId) {
				RoleMenu RoleMenu=new RoleMenu();
				RoleMenu.setUnique_code(IdUtils.uuid());
				RoleMenu.setMenu_code(string);
				RoleMenu.setCreate_time(new Date());
				RoleMenu.setUpdate_time(new Date());
				RoleMenu.setRole_code(roleId);
				int data = systemRoleService.insetrrolemenu(RoleMenu);
			}
		
			result.setCode("1");
			result.setMessage("获取成功");
		
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
	
	}
	
    private String[] String(String parameter) {
		// TODO Auto-generated method stub
		return null;
	}







	//展示权限菜单
	@RequestMapping(value = "/selectmenus")
	@ResponseBody
	public Result selectmenu(HttpServletRequest request) {
		Result result = new Result();
	
		try {
			String parent_code="0";
			List<Menu> menus =systemRoleService.select(parent_code);
			List<treemenu> treemenus=new ArrayList<>();
			for (Menu menu : menus) {
				treemenu tree=new treemenu();
				tree.setId(menu.getUnique_code());
				tree.setLabel(menu.getName());
				Map<Object,Object> map =new HashMap<>();
				//map.put("children",menuChild(menu.getUnique_code()));
				List<Map<Object,Object>> lists=new ArrayList<>();
				lists.add(map);
				tree.setChildren(menuChild(menu.getUnique_code()));
				
				treemenus.add(tree);
			}
			result.setCode("1");
			result.setMessage("获取成功");
			result.setData(treemenus);
			return result;
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
	
	
	}
	public List<twotreemenu> menuChild(String unique_code){
		List<twotreemenu> twomenu=systemRoleService.selecttwo(unique_code);
		//根据一级菜单id查询下面对应的二级菜单
		
		return twomenu;
	}
	
	
	/**
	 *根据角色id获取菜单权限
	 */
	@RequestMapping(value = "selectRoleMenu")
	@ResponseBody
	public Result selectRoleMenu(HttpServletRequest request) {
		Result result=new Result();
		try {
			String roleId=request.getParameter("roleId");
			List<Integer> rolemenu=systemRoleService.getrolemenu(roleId);
			result.setCode("1");
			result.setMessage("获取成功");
			result.setData(rolemenu);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("-1");
			result.setMessage("获取数据异常");
			return result;
		}
		
	}
	
	
}

